<template>
  <!--  查询区-->
  <div class="search">
    <el-form inline :model="coachSearchModel" label-width="80" ref="coachSearchForm">

      <el-form-item label="ID :">
        <el-input v-model="coachSearchModel.id" placeholder="请输入教练id" clearable/>
      </el-form-item>

      <el-form-item label="手机号 :">
        <el-input v-model="coachSearchModel.phone" placeholder="请输入手机号" clearable/>
      </el-form-item>

      <el-form-item label="姓名 :">
        <el-input v-model="coachSearchModel.name" placeholder="请输入姓名" clearable/>
      </el-form-item>

      <el-form-item label="特长 :">
        <el-input v-model="coachSearchModel.specialty" placeholder="请填写特长"/>
      </el-form-item>

      <el-form-item label="邮箱 :">
        <el-input v-model="coachSearchModel.email" placeholder="请填写邮箱"/>
      </el-form-item>

    </el-form>


  </div>

  <!--  按钮区-->
  <div class="action">

    <el-button type="primary" :icon="CirclePlus" @click="add">新增</el-button>
    <el-button type="primary" :icon="Edit" @click="edit">修改</el-button>
    <el-button type="primary" :icon="Search" @click="search()">查询</el-button>
    <el-button type="primary" :icon="Refresh" @click="reset">重置</el-button>
    <el-button type="danger" :icon="Remove" @click="remove">删除</el-button>

  </div>

  <!--  表格区-->
  <div class="grid">
    <el-table :data="coaches" @row-click="tblRowClick" stripe border ref="tblRef" class="data-grid">

      <el-table-column type="selection" width="55" align="center" fixed/>

      <el-table-column prop="id" label="ID" width="100"  fixed />
      <el-table-column label="头像" width="100">
        <template #default="scope">
          <div class="row-avatar" :style="'background-image: url('+(baseUrl+scope.row.avatar)+')'"></div>
        </template>
      </el-table-column>

      <el-table-column prop="phone" label="手机号" width="150" fixed/>
      <el-table-column prop="name" label="姓名" width="150" fixed/>
      <el-table-column prop="specialty" label="特长" width="180"/>
      <el-table-column prop="email" label="邮箱" width="300"/>

      <!--     加入操作按钮   -->
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" :icon="Edit" @click="edit(scope.row)">修改</el-button>
          <el-button type="danger" :icon="Delete" @click="remove(scope.row)">删除</el-button>
          <el-button  type="success" @click="findCourse(scope.row)">查看团课学员</el-button>
          <el-button  type="info" @click="findPrivate(scope.row)">查看私课学员</el-button>
        </template>
      </el-table-column>
    </el-table>

  </div>

  <!--  分页条-->
  <div class="pagination">
    <el-pagination
        v-model:current-page="coachPi.pageNo"
        v-model:page-size="coachPi.pageSize"
        :page-sizes="[2, 3,4,5,6,7,8,9,10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="coachPi.total"
        class="coach-pi"
        background
        @change="coachPiChange"
    />
  </div>
  <!-- 团课/私课学员对话框 -->
  <el-dialog v-model="courseDlgShow" :title="courseDlgTitle" width="600"
             draggable align-center @close="resetMemberForm">
    <el-table :data="courseStudents" stripe border>
      <el-table-column prop="memberId" label="ID" width="80"/>
      <el-table-column label="头像" width="80">
        <template #default="scope">
          <div class="row-avatar"
               :style="'background-image: url('+(baseUrl+scope.row.memberAvatar)+')'"></div>
        </template>
      </el-table-column>
      <el-table-column prop="memberName" label="姓名" width="120"/>
      <el-table-column prop="memberPhone" label="手机号" width="150"/>
      <el-table-column prop="memberEmail" label="邮箱"/>
    </el-table>
  </el-dialog>

  <!--新增/修改对话框-->
  <el-dialog v-model="coachDlgShow" :title="coachDlgTitle" width="600"
             draggable align-center @close="resetCoachForm">
    <el-form label-width="100" label-position="right" ref="coachFormRef"
             :model="coachModel">
      <el-row>
        <el-col :span="16">
          <el-form-item label="手机号 :">
            <el-input v-model="coachModel.phone" placeholder="请输入手机号" clearable/>
          </el-form-item>

          <el-form-item label="姓名 :">
            <el-input v-model="coachModel.name" placeholder="请输入姓名" clearable/>
          </el-form-item>

          <el-form-item label="特长 :">
            <el-input v-model="coachModel.specialty" placeholder="请填写特长" clearable/>
          </el-form-item>

        </el-col>
        <el-col :span="8">
          <el-upload class="avatar" action="/api/coaches/avatar"
                     :on-success="avatarUploadSuccess" :show-file-list="false">
            <div class="img" v-if="coachModel.avatar"
                 :style="'background-image: url('+(baseUrl+coachModel.avatar)+')'"></div>
            <el-icon v-else class="icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-col>
      </el-row>


      <el-form-item label="邮箱：" prop="email">
        <el-input v-model="coachModel.email" placeholder="请输入会员邮箱"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button type="primary" @click="doSubmit">确定</el-button>
        <el-button type="primary" @click="coachDlgShow=false">取消</el-button>
      </div>
    </template>

  </el-dialog>


</template>


<!--样式-->
<style scoped>


.data-grid {
  margin-top: 6px;
}

.avatar {
  width: 140px;
  height: 140px;
  border: 1px dashed #ccc;
  border-radius: 4px;
  margin-left: 8px;
  display: flex;
}

.avatar .icon {
  font-size: 28px;
  justify-content: center;
  align-items: center;
}

.avatar .img {
  width: 140px;
  height: 140px;
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center center;
}

.row-avatar {
  width: 60px;
  height: 60px;
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center center;
  border: 1px solid #ccc;
}
</style>

<style>
.el-upload {
  width: 100%;
}
</style>


<script setup>

import baseUrl from "@/util/constant.js";
import {onMounted, ref, reactive, toRaw, nextTick} from "vue"
import {CirclePlus, Delete, Edit, Plus, Refresh, Remove, Search} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import api from "@/util/api.js";
import {cloneDeep} from "lodash";

function findCourse(row) {
  // 设置对话框标题
  courseDlgTitle.value = `团课学员 - ${row.name}`;
  // 显示对话框
  courseDlgShow.value = true;

  // 调用API获取团课学员数据
  api({
    url: `/coaches/${row.id}/course-students`,
    method: "get"
  }).then(resp => {
    if (resp.success) {
      courseStudents.value = resp.data;
    } else {
      ElMessage.error("获取团课学员失败");
    }
  });
}

let courseDlgShow = ref(false);
let courseDlgTitle = ref("团课学员");
let courseStudents = ref([]); // 存储团课学员数据，应为数组

function findPrivate(row){
  // 显示对话框
  courseDlgShow.value = true;
  // 设置对话框标题
  courseDlgTitle.value = `私课学员 - ${row.name}`;
  // 调用API获取私课学员数据
  api({
    url: `/coaches/${row.id}/private-students`,
    method: "get"
  }).then(resp => {
    if (resp.success) {
      courseStudents.value = resp.data;
    } else {
      ElMessage.error("获取私课学员失败");
    }
  });
}
onMounted(() => {
  search();
});
//定义一个查询教练信息的model
let coachSearchModel = ref({
  phone: null,
  name: null,
  specialty: null,
  id: null,
  avatar: null,
  email: null,
})
//定义表单对象,用于查询条件绑定
let coachSearchForm = ref()

//用于展示页面教练信息、分页信息的模型
let coaches = ref([])
let coachPi = reactive({
  pageNo: 1,
  pageSize: 5,
  total: 0
})

function coachPiChange(pageNo, pageSize) {
  search(pageNo, pageSize)
}

//查询教练信息
async function search(pageNo = 1, pageSize = 5) {
  console.log(toRaw(coachSearchModel.value));
  let params = toRaw(coachSearchModel.value);

  let resp = await api({
    url: "/coaches",
    method: "get",
    params: {
      pageNo,
      pageSize,
      ...params
    }
  })

  coaches.value = resp.data.records;
  coachPi.pageNo = resp.data.current;
  coachPi.pageSize = resp.data.size;
  coachPi.total = resp.data.total;
}

//重置查询条件
function reset() {
  coachSearchModel.value = {
    phone: null,
    name: null,
    specialty: null,
    id: null,
    avatar: null,
    email: null,
  }
}

//定义表格对象 用于选中行
let tblRef = ref()

//表格行点击事件
function tblRowClick(row) {
  tblRef.value.toggleRowSelection(row);
}

//删除教练信息
//只有当用户点击了"确定"，then 里面的函数才会执行
function remove() {
  let rows = tblRef.value.getSelectionRows();
  if (rows.length == 0) {
    ElMessage.warning("请选中您要删除的行")
  } else {
    ElMessageBox.confirm("确定要删除吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(async () => {
      // 删除
      let ids = rows.map(row => row.id);
      let resp = await api({
        url: "/coaches",
        method: "delete",
        data: ids
      })
      if (resp.success) {
        ElMessage.success("删除成功")
        search();
      } else {
        ElMessage.error(resp.msg || "删除失败")
      }
    })
  }
}


////////////////以下全是为新增修改对话框设置的对象////////////////////////
//新增教练信息
//先定义  "新增/修改的表单"
let coachDlgTitle = ref("新增教练信息");
//对话框是否显示，默认不显示
let coachDlgShow = ref(false);
//新增教练信息表单对象
let coachModel = ref({
  phone: null,
  name: null,
  specialty: null,
  id: null,
  avatar: null,
  email: null,
})
//定义对话框的表单对象
let coachFormRef = ref()

//重置对话框信息
function resetCoachForm() {
  coachFormRef.value.resetFields();
}

//定义头像上传函数
function avatarUploadSuccess(resp) {
  coachModel.value.avatar = resp.data;
}

//定义新增还是修改的标志
let mode = "add";

//定义 确定按钮的提交操作
function doSubmit() {
  if (mode === "add") {
    submitAdd();
  }else{
    submitEdit();
  }
}

//新增教练信息
async function add() {
  mode = "add";
  coachDlgShow.value = true;
  coachDlgTitle.value= "新增教练";
}

function submitAdd() {
  let params = toRaw(coachModel.value);

  api({
    url: "/coaches",
    method: "post",
    data: params
  }).then(resp => {
    if (resp.success) {
      coachDlgShow.value = false;
      search();
      ElMessage.success("保存成功")
    }else{
      ElMessage.error("保存失败")
    }
  })

}

//修改教练信息
async function edit() {
  let rows=tblRef.value.getSelectionRows();
  if(rows.length==0){
    ElMessage.warning("请选中您要修改的行")
  }else if(rows.length>1){
    ElMessage.warning("只能选中一行")
  }else{
    mode = "edit";
    coachDlgShow.value=true;
    coachDlgTitle.value="修改会员";

    //深克隆 创建一个新的对象取消双向绑定
    //在下一个时间滴答中操作
    nextTick(() => {
      //深度克隆
      // 如果直接写：memberModel.value = rows[0]
//       那么 memberModel 和 rows[0] 指向同一个对象
//       你在表单中修改数据时，会直接修改原始数据，即使你点了"取消"，表格里的数据也变了
// 使用 cloneDeep 后，memberModel 是一个独立副本，怎么改都不会影响原数据
      //cloneDeep 创建一个完全独立的副本
      //赋值给 memberModel，表单正确回显
      coachModel.value = cloneDeep(toRaw(rows[0]));
    });
  }
}
async function submitEdit(){
  let params = toRaw(coachModel.value);

  let resp= await api({
    url: "/coaches",
    method: "put",
    data: params
  })
  if (resp.success){
    coachDlgShow.value = false;
    search();
    ElMessage.success("修改成功")
  }


}

// 重置学员表单
function resetMemberForm() {
  courseStudents.value = [];
}
</script>
